package com.mooc.swxy.task;

import com.alibaba.fastjson.JSON;
import com.mooc.swxy.pojo.Chapter;
import com.mooc.swxy.pojo.LoadSubmitData;
import com.mooc.swxy.pojo.UserInfo;
import com.mooc.swxy.system.ReqURL;
import com.mooc.swxy.tool.RequestTool;
import com.mooc.swxy.tool.UserTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;

import java.util.*;

/**
 * @author Siaze
 * @date 2022/4/19
 */


public class WkService {

    private static final Map<String,Set<String>> POOL = new HashMap<>();

    private static final Logger logger = LoggerFactory.getLogger(WkService.class);

    private final String courseId;

    private RequestTool requestTool;
    private String nodeId;
    private int studyTime;
    private final List<Chapter.Result.Unit> list;
    private final String token;
    private String studyId;
    private Thread service;
    private String number;
    private String name;


    public WkService(String nodeId, String token, List<Chapter.Result.Unit> list, String courseId) {
        this.nodeId = nodeId;
        this.token = token;
        this.list = list;
        this.courseId = courseId;
    }

    /**
     * 提交学时
     * @param name 章节名称
     * @param length 视频长度
     */
    private void uploadData(String name, int length) {
        requestTool = new RequestTool();
        Map<String, String> params = new HashMap<>(4);
        params.put("token", token);
        params.put("nodeId", nodeId);
        params.put("terminal", "Android");
        params.put("studyTime", String.valueOf(studyTime));
        if (studyId != null) {
            params.put("studyId", studyId);
        }
        try {
            String res = requestTool.postRequest(ReqURL.BASE_URL.concat(ReqURL.COURSE_SUBMIT_URL), MediaType.MULTIPART_FORM_DATA, params, String.class);
            LoadSubmitData loadSubmitData = JSON.parseObject(res, LoadSubmitData.class);
            if(studyId == null){
                studyId = loadSubmitData.getResult().getData().getStudyId();
            }
            logger.info("返回数据：" + res);
            logger.info("{} -  学时提交成功 {}/{}  {} {}"  ,name ,this.studyTime , length, this.studyId, this.name);
        } catch (Exception e) {
            logger.error(" 学时提交失败, 请及时查看");
        }
    }


    /**
     * 通过线程开启任务
     */
    public void start() {
        logger.info("任务开始：");
        UserInfo userInfo = UserTool.getInfo(token);
        this.number = userInfo.getResult().getData().getNumber();
        this.name = userInfo.getResult().getData().getName();
        logger.info("获取用户信息：{}" , userInfo.getResult().getData());

        for (String s1 : POOL.keySet()) {
           for (String s2 : POOL.get(s1)) {
               if(s2.equals(courseId) && s1.equals(number)){
                   logger.info("该用户已经在进行该课程的学习，请勿重复提交");
                   return;
               }
           }
        }
        POOL.computeIfAbsent(number, k -> new HashSet<>());
        POOL.get(number).add(courseId);
        service = new Thread(() -> {
            for (Chapter.Result.Unit unit : list) {
                List<Chapter.Result.Unit.NodeList> chapter = unit.getNodeList();
                for (Chapter.Result.Unit.NodeList nodeList : chapter) {
                    if (nodeList.getVideoState() == 2 || !nodeList.isTabVideo()) {
                        continue;
                    }
                    logger.info("当前任务：{} - {}", nodeList.getName(), nodeList.getVideoDuration());
                    for (int k = 2; k <= nodeList.getVideoDuration() + 20; k += 30) {
                        studyTime = k;
                        nodeId = nodeList.getId();
                        uploadData(nodeList.getName(), nodeList.getVideoDuration());
                        online();
                        try {
                            Thread.sleep(30_000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    studyId = null;
                }
            }
            logger.info("任务结束");
            POOL.remove(number);
        });
        service.start();
    }


    /**
     * 在线
     */
    public void online() {
        Map<String, String> params = new HashMap<>(2);
        params.put("token", token);
        params.put("login", "1");
        try {
            requestTool.postRequest(ReqURL.BASE_URL.concat(ReqURL.ONLINE_URL), MediaType.MULTIPART_FORM_DATA, params, String.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean isProcess(String number, String courseId) {
        return POOL.containsKey(number) && !POOL.get(number).contains(courseId);
    }

    public static Set<String> getProcess(String number) {
        return POOL.get(number) == null ? new HashSet<>() : POOL.get(number);
    }

    public static Map<String,Set<String>> getAllProcess(){
        return POOL;
    }
}

